package cn.seapon.talker;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.seapon.talker.adapters.ChatMsgListAdapter;
import cn.seapon.talker.adapters.ExpressionGridAdapter;
import cn.seapon.talker.adapters.ExpressionPagerAdapter;
import cn.seapon.talker.bean.MessageEntity;
import cn.seapon.talker.common.ChatMsgEntity;
import cn.seapon.talker.common.ChatMsgEntity.ChatMsgType;
import cn.seapon.talker.common.FriendListInfomation.FriendInfomation;
import cn.seapon.talker.common.MessageContent;
import cn.seapon.talker.common.MessageGenre;
import cn.seapon.talker.common.MessageReceiver;
import cn.seapon.talker.common.TMessage;
import cn.seapon.talker.db.MessageEntityDao;
import cn.seapon.talker.infocarrier.Expression;
import cn.seapon.talker.infocarrier.SharedItems;
import cn.seapon.talker.listener.MyOnPageChangeListener;
import cn.seapon.talker.net.SocketUtils;

public class ChatActivity extends Activity implements OnClickListener {
	private static final String TAG = "ChatTestActivity窗口";

	public static ChatActivity context;
	public static List<Expression> expressionList = new ArrayList<Expression>();

	private ExpressionPagerAdapter myPagerAdapter;

	// 用Button的父类TextView来作按钮使用
	private TextView tv_expression, tv_send_msg;
	private EditText et_input;

	// 表情 列数 行数 和每页摆放数
	private int EXPRESSION_COLUMNS = 6;
	private int EXPRESSION_ROWS = 3;
	private int EXPRESSIONS_PER_PAGE = EXPRESSION_COLUMNS * EXPRESSION_ROWS;

	private ViewPager viewPager;
	private LinearLayout expression_panel;
	public LinearLayout expression_box;
	public ArrayList<GridView> grids;
	// --消息列表--//
	private ChatMsgListAdapter chatMessageListAdapter;
	private ArrayList<MessageEntity> msgEntities = new ArrayList<MessageEntity>();
	private ListView listview_chat_box;
	// 广播接受者
	private ChatListChangeBroadcastReceiver receiver;

	private TextView tv_chat_title;
	private FriendInfomation friendInfo;

	private Intent intent;
	private Bundle extra;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chat);
		context = this;

		intent = getIntent();
		extra = intent.getExtras();

		tv_expression = (TextView) findViewById(R.id.tv_expression);
		tv_send_msg = (TextView) findViewById(R.id.tv_send_msg);

		expression_box = (LinearLayout) findViewById(R.id.expression_box);
		expression_panel = (LinearLayout) findViewById(R.id.expression_panel);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		et_input = (EditText) findViewById(R.id.et_input);
		listview_chat_box = (ListView) findViewById(R.id.listview_chat_box);
		tv_chat_title = (TextView) findViewById(R.id.tv_chat_title);

		friendInfo = (FriendInfomation) getIntent().getExtras()
				.getSerializable("friendEntity");
		setFriendTtile();

		tv_expression.setOnClickListener(this);
		tv_send_msg.setOnClickListener(this);
		viewPager.setOnPageChangeListener(new MyOnPageChangeListener());

		/**
		 * 将该联系人的所有西欧系都设置为已经读取
		 */
		if (SharedItems.messageEntityDao.makeAllReaded(
				SharedItems.userInformation.getAccount(), friendInfo.getId()) > 0) {
			Log.d(TAG, "全部清空");
		}
		
		// 创建广播
		receiver = new ChatListChangeBroadcastReceiver(this);
		init();
		SharedItems.currentChat = friendInfo.getId();

		// 加载历史记录
		ArrayList<MessageEntity> entities = SharedItems.messageEntityDao
				.getAllRecord(SharedItems.userInformation.getAccount(),
						friendInfo.getId());
		// ChatDatabaseUtils.getTheHistory(this, friendInfo.getId(), 10);
		msgEntities.addAll(entities);
		refreshList();

	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("cn.seapon.talker.CHAT_LIST_CHANGE");
		registerReceiver(receiver, filter);
		super.onStart();
	}

	@Override
	protected void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}

	private void init() {
		if (null == myPagerAdapter) {
			initExpression();
			// 填充GridView数据
			List<List<Expression>> pages = initGridViewData();
			grids = new ArrayList<GridView>();
			// GridView Padding Left Right Bottom Top Spacing(间距)
			int gv_padding_lr = (int) getResources().getDimension(
					R.dimen.chat_gv_padding_lr);
			int gv_padding_bt = (int) getResources().getDimension(
					R.dimen.chat_gv_padding_bt);
			int gv_spacing = (int) getResources().getDimension(
					R.dimen.chat_gv_spacing);
			// Left Right Width Height
			int chat_dot_margin_lr = (int) getResources().getDimension(
					R.dimen.chat_dot_margin_lr);
			int chat_dot_wh = (int) getResources().getDimension(
					R.dimen.chat_dot_wh);
			// Log.d(TAG,
			// "zhiwei "+gv_padding_lr+"   "+gv_padding_bt+"  "+gv_spacing+"  "+chat_dot_margin_lr+"  "+chat_dot_wh);
			// Log.d(TAG, "表情页数是"+pages.size());
			for (int i = 0; i < pages.size(); i++) {
				List<Expression> expression_list = pages.get(i);
				if (null != expression_list) {
					// 生成当前GridView （将填充到ViewPager上）
					final GridView gridView = new GridView(this);
					gridView.setLayoutParams(new LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.WRAP_CONTENT));
					gridView.setNumColumns(EXPRESSION_COLUMNS);
					gridView.setGravity(Gravity.CENTER);
					gridView.setPadding(gv_padding_lr, gv_padding_bt,
							gv_padding_lr, 0);
					gridView.setHorizontalSpacing(gv_spacing);
					gridView.setVerticalSpacing(gv_spacing);
					gridView.setAdapter(new ExpressionGridAdapter(this,
							expression_list));
					// 点击列表事件处理
					gridView.setOnItemClickListener(new OnItemClickListener() {
						/**
						 * @param arg0
						 *            the AdapterView where the click happened.
						 * @param arg0
						 *            The view within the AdapterView that was
						 *            clicked (this will be a view provided by
						 *            the adapter)
						 * @param arg0
						 *            * The position of the view in the adapter.
						 *            *
						 * @param arg0
						 *            The row id of the item that was clicked.
						 */
						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							Expression expression = (Expression) gridView
									.getItemAtPosition(arg2);
							Log.v("_____________",
									"点击表情_" + expression.getCode());
							// 获取输入框中光标开始的位置
							int index = et_input.getSelectionStart();
							// 获取EditText的文字
							Editable editable = et_input.getEditableText();
							String content_all = editable.toString();
							String content_forward = content_all.substring(0,
									index);// 参数：start end
							Log.v("_____________", "content_all = "
									+ content_all + "|content_forward = "
									+ content_forward + "|");
							// 正则匹配
							String reg = "\\[#[1-9][0-9]?\\]"; // ==》
																// \[#[1-9][0-9]?\]

							/**
							 * 图文结合 imageSpan spannableString
							 */
							// Drawable drawable =
							// ChatTestActivity.this.getResources().getDrawable(expression.getDrableId());
							// drawable.setBounds(0, 0, 25, 25);//这里设置图片的大小
							SpannableString spannableString = new SpannableString(
									expression.getCode());
							ImageSpan imageSpan = new ImageSpan(BitmapFactory
									.decodeResource(getResources(),
											expression.getDrableId()));
							spannableString.setSpan(imageSpan, 0, expression
									.getCode().length(),
									Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

							Log.v("_____________", "spannableString="
									+ spannableString.toString() + "__index="
									+ index);

							// 插入
							if (index < 0 || index >= editable.length()) {
								editable.append(spannableString);
							} else {
								editable.insert(index, spannableString);
							}

						}
					});
					grids.add(gridView);
					// --生成索引图--//
					ImageView iv = new ImageView(this);
					android.widget.LinearLayout.LayoutParams lp = new android.widget.LinearLayout.LayoutParams(
							chat_dot_wh, chat_dot_wh);
					lp.leftMargin = chat_dot_margin_lr;
					lp.rightMargin = chat_dot_margin_lr;
					iv.setLayoutParams(lp);
					if (i == 0) {
						iv.setBackgroundResource(R.drawable.page_focused);
					} else {
						iv.setBackgroundResource(R.drawable.page_unfocused);
					}
					expression_box.addView(iv);
				}
			}
			myPagerAdapter = new ExpressionPagerAdapter(grids);
			viewPager.setAdapter(myPagerAdapter);
		}
	}

	private void setFriendTtile() {
		String nickname = friendInfo.getNickname();
		String remarkname = friendInfo.getRemarkname();
		String friendId = friendInfo.getId();
		if (TextUtils.isEmpty(remarkname)) {
			if (TextUtils.isEmpty(nickname)) {
				tv_chat_title.setText(friendId);
			} else {
				tv_chat_title.setText(nickname + "（" + friendId + "）");
			}
		} else {
			tv_chat_title.setText(remarkname + "（" + friendId + "）");
		}
	}

	/**
	 * 重新获得焦点
	 */
	@Override
	protected void onResume() {
		super.onResume();

	}

	/**
	 * 填充GridView所需要的数据
	 */
	private List<List<Expression>> initGridViewData() {
		List<List<Expression>> pages = new ArrayList<List<Expression>>();
		List<Expression> list = null;
		for (int i = 0; i < expressionList.size(); i++) {
			if (i % EXPRESSIONS_PER_PAGE == 0) {// 一页数据已填充完成
				if (null != list) {
					pages.add(list);
				}
				// 重新创建一页
				list = new ArrayList<Expression>();
			}
			list.add(expressionList.get(i));
			// 不到页尾，但却是最后一个表情
			if (i >= expressionList.size() - 1) {
				pages.add(list);
			}
		}
		// Log.d(TAG,
		// "_____"+pages.size()+" ____ "+pages.get(0).size()+" ____ "+pages.get(1).size()+" ____ "+pages.get(2).size()+" ____ "+pages.get(3).size());
		return pages;
	}

	/**
	 * 加载表情资源到程序中（反射 ）
	 */
	public static void initExpression() {
		for (int i = 1; i <= 64; i++) {
			try {
				Field field = R.drawable.class.getDeclaredField("e_" + i);
				Expression expression = new Expression(field.getInt(null), "[#"
						+ i + "]");
				boolean ret = expressionList.add(expression);
				// Log.d(TAG,
				// "________"+expression.getCode()+"__________"+expression.getDrableId());
			} catch (Exception e) {
				Log.d(TAG, "找不到资源");
				e.printStackTrace();
			}
		}
	}

	private void sendMsg() {
		ChatMsgEntity chatMsgEntity = new ChatMsgEntity();
		chatMsgEntity.setContent(et_input.getText().toString());

		chatMsgEntity.setPosttime(System.currentTimeMillis());
		MessageReceiver receivers = new MessageReceiver();
		receivers.addReceiver(friendInfo.getId());
		chatMsgEntity.setReceivers(receivers);
		chatMsgEntity.setSenderId(SharedItems.userInformation.getAccount());
		chatMsgEntity.setType(ChatMsgType.TEXT);

		sendMessage(chatMsgEntity);
		Log.d(TAG, SharedItems.userInformation.getJSONString());
		Log.d(TAG, chatMsgEntity.getJSONString());
		SharedItems.messageEntityDao.add(MessageEntity
				.translateChatMsgEntityToMessageEntity(chatMsgEntity));
		msgEntities.add(MessageEntity
				.translateChatMsgEntityToMessageEntity(chatMsgEntity));
		refreshList();
		et_input.setText("");
		// 隐藏软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et_input.getWindowToken(), 0);
	}

	private void refreshList() {
		if (null == chatMessageListAdapter) {
			chatMessageListAdapter = new ChatMsgListAdapter(msgEntities, this);
			listview_chat_box.setAdapter(chatMessageListAdapter);
		} else {
			chatMessageListAdapter.setL(msgEntities);
			chatMessageListAdapter.notifyDataSetChanged();
			// 选择最后一条 以此下拉滚动
		}
		listview_chat_box.setSelection(listview_chat_box.getCount());
	}

	private boolean sendMessage(ChatMsgEntity chatMsgEntity) {
		// 发送到服务端
		Socket socket = SharedItems.socket;
		if (socket == null) {
			Log.d(TAG, "套接字未建立！！");
			return false;
		}
		TMessage tm = new TMessage();
		tm.setGenre(MessageGenre.CHAT_MESSAGE);
		tm.setSenderId(SharedItems.userInformation.getAccount());
		tm.setSendTime(System.currentTimeMillis());
		MessageContent messageContent = new MessageContent();
		messageContent.setChatMsgEntity(chatMsgEntity);
		tm.setContent(messageContent);

		try {
			return SocketUtils.writeStringToSocket(socket, tm.getJSonString());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 发送表情
	 */
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tv_expression:
			if (expression_panel.getVisibility() == View.GONE) {
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(this.getCurrentFocus()
								.getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
				expression_panel.setVisibility(View.VISIBLE);
			} else {
				expression_panel.setVisibility(View.GONE);
			}
			break;
		case R.id.tv_send_msg:
			sendMsg();
			break;
		}
	}

	public void showToast(String string) {
		Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
	}

	public void showLog(String string) {
		Log.e(TAG, string);
	}

	public class ChatListChangeBroadcastReceiver extends BroadcastReceiver {

		private Context context;

		public ChatListChangeBroadcastReceiver(Context context) {
			this.context = context;
		}

		@Override
		public void onReceive(Context context2, Intent intent) {
			Bundle bundle = intent.getExtras();
			// Log.e(TAG, bundle.toString());
			String jsonString = (String) bundle.get("newChatMsgEntity");
			if (jsonString == null) {
				return;
			}
			Log.e(TAG, "newChatMsgEntity:" + jsonString);
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(jsonString);
				ChatMsgEntity chatMsgEntity = ChatMsgEntity
						.getObjectFromJson(jsonObject);
				// Log.d(TAG, ""+ChatActivity.this.msgEntities.size());
				// Log.d(TAG, "加入的消息是："+chatMsgEntity.getJSONString());
				ChatActivity.this.msgEntities.add(MessageEntity
						.translateChatMsgEntityToMessageEntity(chatMsgEntity));
				// Log.d(TAG, ""+ChatActivity.this.msgEntities.size());
				ChatActivity.this.refreshList();
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}

}